const defaultScreenSetting = [
  {
    key: '%CN',
    text: '通道名称',
    previewText: ''
  },
  {
    key: '%TLCW',
    text: '总剩余车位',
    previewText: '1000'
  },
  {
    key: '%TVTCW',
    text: '临时剩余车位',
    previewText: '500'
  },
  {
    key: '%T',
    text: '时间',
    previewText: ''
  }
];

const numberToCN = {
  1: '一',
  2: '二',
  3: '三',
  4: '四'
};
import utils from '@/mixins/utils.js';
import { deepCopyObjArray, deepCopyObj } from '@/assets/js/help.js';
export default {
  props: ['oldChannelList'],
  mixins: [utils],
  data() {
    return {
      searchVal: '',
      imgUrlPrefix: '', //图片url访问前缀
      channelList: [],
      curEditChannelItem: null,
      dialogSetting: {
        addChannelDailogVisible: false,
        editChannelDailogVisible: false,
        moreDetailDialogVisible: false,
        screenEditDailogVisible: false,
        screenEditDetailDailogVisible: false,
        editScreenListdialogVisible: false,
        quickSettingDialog: false,
        voiceEditDailogVisible: false,
        screenEditScreenBrightnessDailogVisible: false
      },
      editScreenImgList: [],
      colorList: ['#FF0000', '#00FF00', '#FFFF00', '#0000FF', '#FF00FF', '#FFFFFF'],
      createChannelInitData: {
        entranceName: '',
        entranceType: '',
        enable: true,
        parkGlobalID: this.$route.query.parkId
      },
      quickSetting: {
        typeName: '',
        isIndeterminate: true,
        checkAll: false,
        checkedChannels: [],
        channelList: [],
        searchVal: ''
      },
      originData: null,
      userScreenText: '',
      defaultScreenSetting,
      numberToCN,
      curEditScreenItem: null,
      curEditScreenIndex: null,
      curEditScreenList: null
    };
  },
  created() {
    this.getImgUrlPrefix();
    this.getParkinglotChannels();
  },
  methods: {
    formatEnable(row, column, cellValue, index) {
      return row.enable ? '启用' : '禁用';
    },
    downloadChannelCode() {
      window.open(`/mgr/operatorPark/exportChannelCode?parkID=${this.$route.query.parkId}`);
    },

    submitChannelDetail() {
      this.dialogSetting.moreDetailDialogVisible = false;
      API.fetchPost(`channel/editChannelDetail`, [this.curEditChannelItem]).then(res => {
        this.showToast(`修改通道详情成功`, 1, 2000);
        this.getParkinglotChannels();
        this.setMoreChannel('通道详情');
      });
    },

    submitChannelVoice() {
      this.dialogSetting.voiceEditDailogVisible = false;
      API.fetchPost(`channel/setChannelVoice`, [this.curEditChannelItem]).then(res => {
        this.showToast(`修改语音播报成功`, 1, 2000);
        this.getParkinglotChannels();
        this.setMoreChannel('语音播报');
      });
    },

    setMoreChannel(typeName) {
      setTimeout(() => {
        this.$confirm(`是否把此通道的配置应用到其他通道？`, `快捷配置`, {
          confirmButtonText: '应 用',
          cancelButtonText: '跳 过',
          customClass: 'mgr-msg-box',
          confirmButtonClass: 'el-button el-button--danger',
          dangerouslyUseHTMLString: true
        }).then(() => {
          this.quickSetting.searchVal = '';
          this.quickSetting.checkAll = false;
          this.quickSetting.checkedChannels = [];
          this.quickSetting.isIndeterminate = false;
          this.quickSetting.channelList = this.getQuickChannel(this.curEditChannelItem);
          this.quickSetting.typeName = typeName;
          this.dialogSetting.quickSettingDialog = true;
        });
      }, 2000);
    },

    setChannelsSetting() {
      let params_list = this.quickSetting.channelList.filter(item =>
        this.quickSetting.checkedChannels.includes(item.id)
      );
      params_list = JSON.parse(JSON.stringify(params_list));

      if (this.quickSetting.typeName === '通道详情') {
        params_list = params_list.map(item => {
          if (this.curEditChannelItem.entranceType === 1) {
            return Object.assign({}, item, {
              deviceNetModel: this.curEditChannelItem.deviceNetModel,
              normalCarPassMode: this.curEditChannelItem.normalCarPassMode,
              localVipCarPassMode: this.curEditChannelItem.localVipCarPassMode,
              dynamicVipToNormalMode: this.curEditChannelItem.dynamicVipToNormalMode,
              noChannelMode: this.curEditChannelItem.noChannelMode,
              noPlatePassMode: this.curEditChannelItem.noPlatePassMode,
              visitorListPassMode: this.curEditChannelItem.visitorListPassMode,
              redListPassMode: this.curEditChannelItem.redListPassMode,
              blacklistPassMode: this.curEditChannelItem.blacklistPassMode
            });
          }

          if (this.curEditChannelItem.entranceType === 2) {
            return Object.assign({}, item, {
              deviceNetModel: this.curEditChannelItem.deviceNetModel,
              normalCarPassMode: this.curEditChannelItem.normalCarPassMode,
              normalNoRecordPassMode: this.curEditChannelItem.normalNoRecordPassMode,
              localVipCarPassMode: this.curEditChannelItem.localVipCarPassMode,
              vipNotInPassMode: this.curEditChannelItem.vipNotInPassMode,
              noPlatePassMode: this.curEditChannelItem.noPlatePassMode,
              visitorListPassMode: this.curEditChannelItem.visitorListPassMode,
              redListPassMode: this.curEditChannelItem.redListPassMode,
              blacklistPassMode: this.curEditChannelItem.blacklistPassMode
            });
          }
        });

        API.fetchPost(`channel/editChannelDetail`, params_list).then(res => {
          this.showToast(`操作成功`, 1, 2000);
          this.getParkinglotChannels();
          this.dialogSetting.quickSettingDialog = false;
        });
      }

      if (this.quickSetting.typeName === '语音播报') {
        params_list = params_list.map(item => {
          return Object.assign({}, item, {
            timeArray: this.curEditChannelItem.timeArray,
            deviceVolume: this.curEditChannelItem.deviceVolume
          });
        });
        API.fetchPost(`channel/setChannelVoice`, params_list).then(res => {
          this.showToast(`操作成功`, 1, 2000);
          this.getParkinglotChannels();
          this.dialogSetting.quickSettingDialog = false;
        });
      }

      if (this.quickSetting.typeName === '静态屏显') {
        params_list.forEach(item => {
          if (item.displayVersion === -1) {
            if (
              item.displayType !== this.curEditChannelItem.uiOpt.displayType ||
              this.curEditChannelItem.displayFrontColor !== item.displayFrontColor ||
              this.curEditChannelItem.displayContent !== item.displayContent
            ) {
              item.displayVersion = 0;
            }
          }
        });
        params_list = params_list.map(item => {
          return Object.assign({}, item, {
            displayContent: this.curEditChannelItem.displayContent,
            displayFrontColor: this.curEditChannelItem.displayFrontColor,
            displayType: this.curEditChannelItem.displayType,
            displayViewModel: this.curEditChannelItem.displayViewModel,
            displayPicShowType: this.curEditChannelItem.displayPicShowType
          });
        });
        API.fetchPost(`channel/setChannelDisplay`, params_list).then(res => {
          this.showToast(`操作成功`, 1, 2000);
          this.getParkinglotChannels();
          this.dialogSetting.quickSettingDialog = false;
        });
      }

      if (this.quickSetting.typeName === '屏幕亮度配置') {
        params_list = params_list.map(item => {
          return Object.assign({}, item, {
            screenBrightness: this.curEditChannelItem.screenBrightness
          });
        });
        API.fetchPost(`channel/setChannelScreenBrightness`, params_list).then(res => {
          this.showToast(`操作成功`, 1, 2000);
          this.getParkinglotChannels();
          this.dialogSetting.quickSettingDialog = false;
        });
      }
    },

    getQuickChannel(channelItem) {
      return this.channelList.filter(
        item => item.id !== channelItem.id && item.entranceType === channelItem.entranceType
      );
    },

    handleQuickChannelsCheckAllChange(val) {
      if (val) {
        this.quickSetting.checkedChannels = this.quickSetting.channelList.map(item => item.id);
      } else {
        this.quickSetting.checkedChannels = [];
      }
      this.quickSetting.isIndeterminate = false;
    },

    handleCheckedQuickChannelsChange(value) {
      let checkedCount = value.length;
      this.quickSetting.checkAll = checkedCount === this.quickSetting.channelList.length;
      this.quickSetting.isIndeterminate = checkedCount > 0 && checkedCount < this.quickSetting.channelList.length;
    },

    setEDBrightness() {
      this.curEditChannelItem.uiOpt.screenBrightness.startSetting.brightness = 70;
      this.curEditChannelItem.uiOpt.screenBrightness.endSetting.brightness = 100;
    },

    setLCDBrightness() {
      this.curEditChannelItem.uiOpt.screenBrightness.startSetting.brightness = 30;
      this.curEditChannelItem.uiOpt.screenBrightness.endSetting.brightness = 50;
    },

    setChannelScreenBrightness() {
      const startArray = this.curEditChannelItem.uiOpt.screenBrightness.startSetting.timeArray;
      const endArray = this.curEditChannelItem.uiOpt.screenBrightness.endSetting.timeArray;
      if (startArray.concat(endArray).filter(item => item === 'NaN:NaN').length) {
        this.showToast(`时间段不能为空`, 2, 2000);
        return;
      }

      this.dialogSetting.screenEditScreenBrightnessDailogVisible = false;

      let screenBrightness = [];

      for (let key in this.curEditChannelItem.uiOpt.screenBrightness) {
        screenBrightness.push({
          brightness: this.curEditChannelItem.uiOpt.screenBrightness[key].brightness,
          time: `${this.curEditChannelItem.uiOpt.screenBrightness[key].timeArray[0]}-${
            this.curEditChannelItem.uiOpt.screenBrightness[key].timeArray[1]
          }`
        });
      }

      this.curEditChannelItem.screenBrightness = JSON.stringify(screenBrightness);

      API.fetchPost(`channel/setChannelScreenBrightness`, [this.curEditChannelItem]).then(res => {
        this.showToast(`修改屏幕亮度成功`, 1, 2000);
        this.getParkinglotChannels();
        this.setMoreChannel('屏幕亮度配置');
      });
    },

    setChannelDisplay() {
      this.dialogSetting.screenEditDailogVisible = false;
      const old_displayContent = JSON.parse(JSON.stringify(this.curEditChannelItem.displayContent));
      const old_displayFrontColor = JSON.parse(JSON.stringify(this.curEditChannelItem.displayFrontColor));
      if (this.curEditChannelItem.displayType === 0) {
        let displayContent = this.curEditChannelItem.uiOpt.displayDefaultArray.map(item => {
          return item.map(item => {
            return item.key;
          });
        });

        this.curEditChannelItem.displayContent = JSON.stringify({
          displayContentArray: displayContent
        });

        this.curEditChannelItem.displayFrontColor = '';
      }

      if (this.curEditChannelItem.displayType === 1) {
        let displayContent = this.curEditChannelItem.uiOpt.displayLEDArray.map((item, index) => {
          if (index < 2) {
            return item.map(item => {
              return item.key;
            });
          } else {
            if (item.length) {
              if (item[0].key === '%PTQR') {
                return ['%PTQR'];
              } else if (item[0].key === '%PTDM') {
                return ['%PTDM', item[0].images[0]];
              } else if (item[0].key === 'images') {
                return item[0].images;
              }
            } else {
              return [];
            }
          }
        });

        if (displayContent[2].length && displayContent[2][0] !== '%PTQR' && displayContent[2][0] !== '%PTDM') {
          this.curEditChannelItem.displayPicShowType = 2;
        } else if (!displayContent[2].length) {
          this.curEditChannelItem.displayPicShowType = 0;
        }

        this.curEditChannelItem.displayFrontColor = JSON.stringify({
          displayFrontColor: this.curEditChannelItem.uiOpt.LEDFontColorArray
        });

        this.curEditChannelItem.displayContent = JSON.stringify({
          displayContentArray: displayContent
        });
      }

      if (this.curEditChannelItem.displayType === 2) {
        let displayContent = this.curEditChannelItem.uiOpt.displayLCDArray.map((item, index) => {
          if (index < 2) {
            return item.map(item => {
              return item.key;
            });
          } else {
            if (item.length) {
              return item[0].images;
            } else {
              return [];
            }
          }
        });

        if (displayContent[2].length) {
          this.curEditChannelItem.displayPicShowType = 2;
        } else if (!displayContent[2].length) {
          this.curEditChannelItem.displayPicShowType = 0;
        }

        this.curEditChannelItem.displayFrontColor = JSON.stringify({
          displayFrontColor: this.curEditChannelItem.uiOpt.LCDFontColorArray
        });

        this.curEditChannelItem.displayContent = JSON.stringify({
          displayContentArray: displayContent
        });
      }

      if (this.curEditChannelItem.displayVersion === -1) {
        if (
          this.curEditChannelItem.displayType !== this.curEditChannelItem.uiOpt.displayType ||
          this.curEditChannelItem.displayFrontColor !== old_displayFrontColor ||
          this.curEditChannelItem.displayContent !== old_displayContent
        ) {
          this.curEditChannelItem.displayVersion = 0;
        }
      }

      API.fetchPost(`channel/setChannelDisplay`, [this.curEditChannelItem]).then(res => {
        this.showToast(`修改静态屏显成功`, 1, 2000);
        this.getParkinglotChannels();
        this.setMoreChannel('静态屏显');
      });
    },

    setChannelStatus(item) {
      this.$confirm(
        `确定${item.enable ? '禁用' : '启用'}${item.entranceName}？`,
        `${item.enable ? '禁用' : '启用'}通道-${item.entranceName}`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'mgr-msg-box',
          confirmButtonClass: 'el-button el-button--danger',
          dangerouslyUseHTMLString: true
        }
      ).then(async () => {
        if (item.enable) {
          const enableClose = await this.checkChannelStatus(item.id);
          if (!enableClose) return;
          API.fetchPost(`channel/setChannelEnable`, {
            id: item.id,
            enable: !item.enable
          }).then(res => {
            this.showToast(`${item.enable ? '禁用' : '启用'}通道成功`, 1, 2000);
            this.getParkinglotChannels();
          });
        } else {
          API.fetchPost(`channel/setChannelEnable`, {
            id: item.id,
            enable: !item.enable
          }).then(res => {
            this.showToast(`${item.enable ? '禁用' : '启用'}通道成功`, 1, 2000);
            this.getParkinglotChannels();
          });
        }
      });
    },

    checkChannelStatus(id) {
      const self = this;
      return new Promise((resolve, reject) => {
        API.fetchGet('/operatorPark/checkChannel', {
          parkID: self.$route.query.parkId,
          channelID: id
        }).then(
          res => {
            if (res.status == 1 && res.resultCode == -1) {
              self.showToast('该通道有收费员上班，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -2) {
              self.showToast('该通道当前为潮汐通道，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -3) {
              self.showToast('该通道为潮汐通道并为上班状态，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -4) {
              self.showToast('该通道已绑定设备,请先到设备管理中解绑设备', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == 0) {
              resolve(true);
            }
          },
          err => {}
        );
      });
    },

    editChannelName(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.dialogSetting.editChannelDailogVisible = true;
      if (this.$refs['curEditChannelItem']) {
        this.$refs['curEditChannelItem'].resetFields();
      }
    },

    removeChannel(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.$confirm(`确定删除${curItem.entranceName}？`, `删除通道-${curItem.entranceName}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'mgr-msg-box',
        confirmButtonClass: 'el-button el-button--danger',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        const isDel = await this.checkChannelStatus(curItem.id);
        if (!isDel) return;
        API.fetchPost(`channel/delChannel`, {
          id: curItem.id
        }).then(res => {
          this.showToast('删除通道成功', 1, 2000);
          this.getParkinglotChannels();
        });
      });
    },

    setChannelMoreDetail(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.dialogSetting.moreDetailDialogVisible = true;
    },

    setScreenSetting(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.dialogSetting.screenEditDailogVisible = true;
    },

    setScreenBrightnessSetting(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.dialogSetting.screenEditScreenBrightnessDailogVisible = true;
    },

    setVoiceSetting(curItem) {
      this.curEditChannelItem = deepCopyObj(curItem);
      this.dialogSetting.voiceEditDailogVisible = true;
    },

    addChannelDialogShow() {
      this.createChannelInitData.entranceName = '';
      this.createChannelInitData.entranceType = '';
      this.dialogSetting.addChannelDailogVisible = true;
      if (this.$refs['createChannelInitData']) {
        this.$refs['createChannelInitData'].resetFields();
      }
    },

    screenBrightnessLightStartTimeChange(val) {
      const d = new Date();
      let cur_d = new Date(`${d.getFullYear}/${d.getMonth() + 1}/${d.getDate()} ${val}:00`);
      cur_d.setMinutes(cur_d.getMinutes() - 1);

      this.curEditChannelItem.uiOpt.screenBrightness.endSetting.timeArray.splice(
        1,
        1,
        `${cur_d.getHours() < 10 ? '0' + cur_d.getHours() : cur_d.getHours()}:${
          cur_d.getMinutes() < 10 ? '0' + cur_d.getMinutes() : cur_d.getMinutes()
        }`
      );
    },

    screenBrightnessLightEndTimeChange(val) {
      let d = new Date();

      let cur_d = new Date(`${d.getFullYear}/${d.getMonth() + 1}/${d.getDate()} ${val}:00`);
      cur_d.setMinutes(cur_d.getMinutes() + 1);

      this.curEditChannelItem.uiOpt.screenBrightness.endSetting.timeArray.splice(
        0,
        1,
        `${cur_d.getHours() < 10 ? '0' + cur_d.getHours() : cur_d.getHours()}:${
          cur_d.getMinutes() < 10 ? '0' + cur_d.getMinutes() : cur_d.getMinutes()
        }`
      );
    },

    screenBrightnessDarkStartTimeChange(val) {
      const d = new Date();
      let cur_d = new Date(`${d.getFullYear}/${d.getMonth() + 1}/${d.getDate()} ${val}:00`);
      cur_d.setMinutes(cur_d.getMinutes() - 1);

      this.curEditChannelItem.uiOpt.screenBrightness.startSetting.timeArray.splice(
        1,
        1,
        `${cur_d.getHours() < 10 ? '0' + cur_d.getHours() : cur_d.getHours()}:${
          cur_d.getMinutes() < 10 ? '0' + cur_d.getMinutes() : cur_d.getMinutes()
        }`
      );
    },

    screenBrightnessDarkEndTimeChange(val) {
      const d = new Date();
      let cur_d = new Date(`${d.getFullYear}/${d.getMonth() + 1}/${d.getDate()} ${val}:00`);
      cur_d.setMinutes(cur_d.getMinutes() + 1);
      this.curEditChannelItem.uiOpt.screenBrightness.startSetting.timeArray.splice(
        0,
        1,
        `${cur_d.getHours() < 10 ? '0' + cur_d.getHours() : cur_d.getHours()}:${
          cur_d.getMinutes() < 10 ? '0' + cur_d.getMinutes() : cur_d.getMinutes()
        }`
      );
    },

    checkChannel(rule, value, callback) {
      if (value === '') {
        callback(new Error('通道名称不能为空'));
      }
      let nameList = [];
      this.channelList.forEach(item => {
        if (item.entranceName) {
          nameList.push(item.entranceName);
        }
      });

      if (nameList.indexOf(value) !== -1) {
        callback(new Error('通道名称重复'));
        return;
      }
      callback();
    },

    async createChannel() {
      const isTest = await this.testForm('createChannelInitData');
      if (!isTest) return;
      this.dialogSetting.addChannelDailogVisible = false;
      API.fetchPost(`channel/addChannel`, this.createChannelInitData).then(res => {
        this.showToast('新增通道成功', 1, 2000);
        this.getParkinglotChannels();
      });
    },

    async submitEditChannelName() {
      const isTest = await this.testForm('curEditChannelItem');
      if (!isTest) return;
      this.dialogSetting.editChannelDailogVisible = false;
      API.fetchPost(`channel/editChannelBase`, {
        entranceName: this.curEditChannelItem.entranceName,
        id: this.curEditChannelItem.id
      }).then(res => {
        this.showToast('修改通道成功', 1, 2000);
        this.getParkinglotChannels();
      });
    },

    testForm(formName) {
      return new Promise(resolve => {
        this.$refs[formName].validate(valid => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    // 色块选颜色
    handleChangeTheme(curItem, index, item) {
      curItem.splice(index, 1, item);
    },
    // 删除图片-led
    handleEditScreenListRemove(file) {
      const fileName = file.name;

      this.editScreenImgList = this.editScreenImgList.filter(item => {
        return !item.url.includes(fileName);
      });
    },
    handleEditScreenImgListChange(file) {
      let self = this;
      const isJPG = file.raw.type === 'image/jpeg';
      const isLt200k = file.size > 200 * 1024;
      const isLt2M = file.size > 2 * 1024 * 1024;

      if (!isJPG) {
        this.$alert('请上传jpg格式图片!', '温馨提示!', {
          confirmButtonText: '确定',
          callback: action => {
            $('ul.el-upload-list--picture')
              .find('li.is-ready')
              .remove();
          }
        });
        return;
      }

      if (isLt200k && this.curEditChannelItem.displayType === 1) {
        this.showToast('图片大小不超过200kb！', 0);
        return;
      }

      if (isLt2M && this.curEditChannelItem.displayType === 2) {
        this.showToast('图片大小不超过2M！！', 0);
        return;
      }

      let reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e) {
        const base64Img = this.result.split(';base64,')[1];
        self.uploadSrceenImg(base64Img);
      };
    },
    uploadSrceenImg(base64Img) {
      let self = this;
      API.fetchPost('operatorPark/uploadChannelLogo.do', {
        channelLogoId: `${this.$route.query.id}_${this.curEditChannelItem.id}_${Date.parse(new Date())
          .toString()
          .substr(0, 10)}`,
        channelLogo: base64Img
      }).then(res => {
        self.showToast('操作成功！', 1, 1500);
        this.editScreenImgList.push({
          name: res.message.split('/')[res.message.split('/').length - 1],
          url: this.imgUrlPrefix + res.message
        });
      });
    },
    // LED上传图片-确认
    saveScreenListChange() {
      if (this.curEditChannelItem.displayType === 1) {
        this.curEditChannelItem.uiOpt.displayLEDArray[2] = [
          {
            key: 'images',
            text: '',
            previewText: '',
            images: this.editScreenImgList.map(item => {
              return item.url.split(this.imgUrlPrefix)[1];
            })
          }
        ];
      }

      if (this.curEditChannelItem.displayType === 2) {
        this.curEditChannelItem.uiOpt.displayLCDArray[2] = [
          {
            key: 'images',
            text: '',
            previewText: '',
            images: this.editScreenImgList.map(item => {
              return item.url.split(this.imgUrlPrefix)[1];
            })
          }
        ];
      }

      this.dialogSetting.editScreenListdialogVisible = false;
    },
    //获取图片访问域名
    getImgUrlPrefix() {
      let _this = this;
      API.fetchGet('operatorPark/getURLPrefix.do', {}).then(
        res => {
          if (res.status == 1) {
            _this.imgUrlPrefix = res.message;
          }
        },
        err => {}
      );
    },
    //上传图片
    handleChange(file, fileList) {
      let self = this;
      let max_size = 200; // kb
      if (fileList.length > 0) {
        self.logoList = [file];
        if (file.raw) {
          if (!/.(jpg|jpeg|JPG)$/.test(file.raw.type)) {
            self.showToast('请上传jpg格式图片!', 0);
            return;
          }
          if (file.size > max_size * 1024) {
            self.showToast('图片大小不超过200kb！', 0);
            return;
          }
          let reader = new FileReader();
          reader.readAsDataURL(file.raw);
          reader.onload = function(e) {
            let _res = this.result;
            self.logoImg = _res.split(';base64,')[1];
            if (self.logoImg) {
              self.uploadLogo(file.name);
            }
          };
        }
      } else {
        this.logoList = [];
      }
    },
    //上传图片
    uploadLogo(name) {
      let self = this;
      let params = {
        channelLogoId: self.channelLogoId,
        channelLogo: self.logoImg
      };
      API.fetchPost('operatorPark/uploadChannelLogo.do', params).then(
        res => {
          self.showToast('操作成功！', 1, 1500);
          let num = self.createRandomNumber();
          self.curUploadQrCodeParams.qrcodePicUrl = res.message + '?' + num;
          self.logoList = [];
          self.logoImg = null;
        },
        err => {
          console.log(err);
        }
      );
    },
    getParkinglotChannels() {
      API.fetchGet(`/operatorPark/byParkID/${this.$route.query.parkId}`).then(
        res => {
          this.originData = res.data;
          this.channelList = this.formatInitData(JSON.parse(JSON.stringify(res.data)));
        },
        err => {}
      );
    },
    formatInitData(channelList) {
      let result = [];
      const d = new Date();
      channelList.forEach(item => {
        let uiOpt = {
          displayDefaultArray: [
            [
              {
                key: '%CN',
                text: '通道名称',
                previewText: item.entranceName
              }
            ],
            [
              {
                key: '%T',
                text: '时间',
                previewText: `${d.getHours()}:${d.getMinutes()}`
              }
            ],
            [],
            []
          ], //屏显默认设置
          displayLEDArray: [
            [
              {
                key: '%CN',
                text: '通道名称',
                previewText: item.entranceName
              }
            ],
            [
              {
                key: '%T',
                text: '时间',
                previewText: `${d.getHours()}:${d.getMinutes()}`
              }
            ],
            []
          ],
          displayLCDArray: [
            [
              {
                key: '%CN',
                text: '通道名称',
                previewText: item.entranceName
              }
            ],
            [
              {
                key: '%T',
                text: '时间',
                previewText: `${d.getHours()}:${d.getMinutes()}`
              }
            ],
            []
          ],
          LCDFontColorArray: ['#FFFFFF', '#FFFFFF'],
          LEDFontColorArray: ['#FF0000', '#FF0000'],
          screenBrightness: {},
          displayType: item.displayType
        };

        if (!item.screenBrightness) {
          uiOpt.screenBrightness.startSetting = {
            brightness: 70,
            timeArray: ['06:00', '18:59']
          };

          uiOpt.screenBrightness.endSetting = {
            brightness: 100,
            timeArray: ['19:00', '05:59']
          };
        } else {
          const parse_screenBrightness = JSON.parse(item.screenBrightness);
          uiOpt.screenBrightness.startSetting = {
            brightness: parse_screenBrightness[0].brightness,
            timeArray: [parse_screenBrightness[0].time.split('-')[0], parse_screenBrightness[0].time.split('-')[1]]
          };

          uiOpt.screenBrightness.endSetting = {
            brightness: parse_screenBrightness[1].brightness,
            timeArray: [parse_screenBrightness[1].time.split('-')[0], parse_screenBrightness[1].time.split('-')[1]]
          };
        }

        const parse_displayContent = JSON.parse(item.displayContent);
        const parse_displayFrontColor = item.displayFrontColor ? JSON.parse(item.displayFrontColor) : '';

        if (item.displayType === 0) {
          parse_displayContent.displayContentArray.forEach((screenItem, index) => {
            if (!screenItem.length) {
              uiOpt.displayDefaultArray[index] = [];
              return;
            }

            let o = [];
            screenItem.forEach(keyItem => {
              const keys = ['%CN', '%T', '%TLCW', '%TVTCW'];

              if (!keyItem) {
                return;
              }

              if (keyItem === '%CN') {
                o.push({
                  key: keyItem,
                  text: '通道名称',
                  previewText: item.entranceName
                });
              }

              if (keyItem === '%T') {
                const d = new Date();
                o.push({
                  key: keyItem,
                  text: '时间',
                  previewText: `${d.getHours()}:${d.getMinutes()}`
                });
              }

              if (keyItem === '%TLCW') {
                o.push({
                  key: '%TLCW',
                  text: '总剩余车位',
                  previewText: '1000'
                });
              }

              if (keyItem === '%TVTCW') {
                o.push({
                  key: '%TVTCW',
                  text: '临时剩余车位',
                  previewText: '500'
                });
              }

              if (keys.indexOf(keyItem) === -1) {
                o.push({
                  key: keyItem,
                  previewText: keyItem,
                  text: 'userText'
                });
              }
            });
            uiOpt.displayDefaultArray[index] = o;
          });
        }

        if (item.displayType === 1) {
          uiOpt.LEDFontColorArray = parse_displayFrontColor.displayFrontColor;
          parse_displayContent.displayContentArray.forEach((screenItem, index) => {
            if (!screenItem.length) {
              uiOpt.displayLEDArray[index] = [];
              return;
            }
            let o = [];
            if (index < 2) {
              screenItem.forEach(keyItem => {
                // '%PTQR':屏显(二维码类型);'%PTDM':屏显(图片类型)
                const keys = ['%CN', '%T', '%TLCW', '%TVTCW', '%PTQR', '%PTDM'];

                if (!keyItem) {
                  return;
                }

                if (keyItem === '%CN') {
                  o.push({
                    key: keyItem,
                    text: '通道名称',
                    previewText: item.entranceName
                  });
                }

                if (keyItem === '%T') {
                  o.push({
                    key: keyItem,
                    text: '时间',
                    previewText: `${d.getHours()}:${d.getMinutes()}`
                  });
                }

                if (keyItem === '%TLCW') {
                  o.push({
                    key: '%TLCW',
                    text: '总剩余车位',
                    previewText: '1000'
                  });
                }

                if (keyItem === '%TVTCW') {
                  o.push({
                    key: '%TVTCW',
                    text: '临时剩余车位',
                    previewText: '500'
                  });
                }

                if (keys.indexOf(keyItem) === -1) {
                  o.push({
                    key: keyItem,
                    previewText: keyItem,
                    text: 'userText'
                  });
                }
              });
            }
            const keys = ['%CN', '%T', '%TLCW', '%TVTCW', '%PTQR', '%PTDM'];
            // 第三行
            if (index === 2) {
              if (screenItem.includes('%PTQR')) {
                o.push({
                  key: '%PTQR',
                  text: '',
                  previewText: '',
                  images: []
                });
              } else if (screenItem.includes('%PTDM')) {
                o.push({
                  key: '%PTDM',
                  text: '',
                  previewText: '',
                  images: [screenItem[1]]
                });
              } else {
                o.push({
                  key: 'images',
                  text: '',
                  previewText: '',
                  images: screenItem
                });
              }
            }
            uiOpt.displayLEDArray[index] = o;
          });
        }

        if (item.displayType === 2) {
          uiOpt.LCDFontColorArray = parse_displayFrontColor.displayFrontColor;
          parse_displayContent.displayContentArray.forEach((screenItem, index) => {
            if (!screenItem.length) {
              uiOpt.displayLCDArray[index] = [];
              return;
            }
            let o = [];
            if (index < 2) {
              screenItem.forEach(keyItem => {
                // '%PTQR':屏显(二维码类型);'%PTDM':屏显(图片类型)
                const keys = ['%CN', '%T', '%TLCW', '%TVTCW', '%PTQR', '%PTDM'];

                if (!keyItem) {
                  return;
                }

                if (keyItem === '%CN') {
                  o.push({
                    key: keyItem,
                    text: '通道名称',
                    previewText: item.entranceName
                  });
                }

                if (keyItem === '%T') {
                  const d = new Date();
                  o.push({
                    key: keyItem,
                    text: '时间',
                    previewText: `${d.getHours()}:${d.getMinutes()}`
                  });
                }

                if (keyItem === '%TLCW') {
                  o.push({
                    key: '%TLCW',
                    text: '总剩余车位',
                    previewText: '1000'
                  });
                }

                if (keyItem === '%TVTCW') {
                  o.push({
                    key: '%TVTCW',
                    text: '临时剩余车位',
                    previewText: '500'
                  });
                }

                if (keys.indexOf(keyItem) === -1) {
                  o.push({
                    key: keyItem,
                    previewText: keyItem,
                    text: 'userText'
                  });
                }
              });
            }
            const keys = ['%CN', '%T', '%TLCW', '%TVTCW', '%PTQR', '%PTDM'];
            // 第三行
            if (index === 2) {
              o.push({
                key: 'images',
                text: '',
                previewText: '',
                images: screenItem
              });
            }
            uiOpt.displayLCDArray[index] = o;
          });
        }

        item.uiOpt = uiOpt;
        result.push(item);
      });

      return result;
    },
    setCurTab(item, tabItem) {
      if (tabItem === '静态屏显') {
        item.uiOpt.displayContentArray.forEach(sitem => {
          sitem.forEach(pitem => {
            if (pitem.text === '通道名称') {
              pitem.previewText = item.entranceName ? item.entranceName : '通道名称';
            }
            if (pitem.text === '时间') {
              const d = new Date();
              pitem.previewText = `${d.getHours()}:${d.getMinutes()}`;
            }
          });
        });
      }
      item.uiOpt.curTab = tabItem;
    },
    editScreenShow(screenItem, channelItem, list, index) {
      this.userScreenText = '';
      this.curEditScreenItem = JSON.parse(JSON.stringify(screenItem));
      this.curEditScreenList = list;
      this.defaultScreenSetting.forEach(pitem => {
        if (pitem.text === '通道名称') {
          pitem.previewText = channelItem.entranceName ? channelItem.entranceName : '通道名称';
        }
        if (pitem.text === '时间') {
          const d = new Date();
          pitem.previewText = `${d.getHours()}:${d.getMinutes()}`;
        }
      });
      this.curEditScreenIndex = index;
      this.dialogSetting.screenEditDetailDailogVisible = true;
    },
    addTagToScreenShow(item) {
      const isLen = this.curEditScreenItem.filter(sitem => sitem.text === item.text).length;
      if (!isLen) {
        this.curEditScreenItem.push(item);
      } else {
        return;
      }
    },
    addUserScreenText() {
      if (!this.userScreenText) return;
      const userScreenText = {
        key: this.userScreenText,
        previewText: this.userScreenText,
        text: 'userText'
      };
      this.curEditScreenItem.push(userScreenText);
    },
    delTag(index) {
      this.curEditScreenItem.splice(index, 1);
    },

    editScreenImg(item) {
      if (this.curEditChannelItem.displayType === 1) {
        if (!item.length || item[0].key === '%PTQR') {
          this.editScreenImgList = [];
        } else if (item[0].key === '%PTDM' || item[0].key === 'images') {
          this.editScreenImgList = item[0].images.map(item => {
            return {
              name: item.split('/')[item.split('/').length - 1],
              url: this.imgUrlPrefix + item
            };
          });
        }
      } else if (this.curEditChannelItem.displayType === 2) {
        if (item.length) {
          this.editScreenImgList = item[0].images.map(item => {
            return {
              name: item.split('/')[item.split('/').length - 1],
              url: this.imgUrlPrefix + item
            };
          });
        } else {
          this.editScreenImgList = [];
        }
      }

      this.dialogSetting.editScreenListdialogVisible = true;
    },
    confirmScreen() {
      this.curEditScreenList.splice(this.curEditScreenIndex, 1, this.curEditScreenItem);
      this.dialogSetting.screenEditDetailDailogVisible = false;
    },

    checkChannelStatus(id) {
      const self = this;
      return new Promise((resolve, reject) => {
        API.fetchGet('/operatorPark/checkChannel', {
          parkID: self.$route.query.parkId,
          channelID: id
        }).then(
          res => {
            if (res.status == 1 && res.resultCode == -1) {
              self.showToast('该通道有收费员上班，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -2) {
              self.showToast('该通道当前为潮汐通道，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -3) {
              self.showToast('该通道为潮汐通道并为上班状态，不允许删除或关闭', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == -4) {
              self.showToast('该通道已绑定设备,请先到设备管理中解绑设备', 2, 2000);
              resolve(false);
            } else if (res.status == 1 && res.resultCode == 0) {
              resolve(true);
            }
          },
          err => {}
        );
      });
    }
  },
  computed: {
    filterQuickChannelList() {
      if (this.quickSetting.searchVal) {
        return this.quickSetting.channelList.filter(item => item.entranceName.includes(this.quickSetting.searchVal));
      } else {
        return [];
      }
    },
    filterSearchChannelList() {
      if (this.searchVal && this.channelList.length) {
        return this.channelList.filter(item => item.entranceName.includes(this.searchVal));
      } else {
        return [];
      }
    }
  }
};
